// 通用 CSV 导出工具
export function exportToCSV<T extends Record<string, any>>(
  rows: T[],
  options?: { filename?: string; headers?: Record<string, string>; columns?: (keyof T)[] }
) {
  const filename = (options?.filename || `export_${Date.now()}`).replace(/\s+/g, '_') + '.csv'
  if (!rows || rows.length === 0) {
    download('', filename)
    return
  }
  const columns: (keyof T)[] = options?.columns || (Object.keys(rows[0]) as (keyof T)[])
  const headersMap = options?.headers || {}
  const headerLine = columns.map(key => escapeCSV(headersMap[String(key)] || String(key))).join(',')
  const lines = rows.map(row => columns.map(key => escapeCSV(formatCell(row[key]))).join(','))
  const csvContent = [headerLine, ...lines].join('\n')
  download(csvContent, filename)
}

function escapeCSV(value: string) {
  if (value == null) return ''
  const needQuote = /[",\n]/.test(value)
  const escaped = value.replace(/"/g, '""')
  return needQuote ? `"${escaped}"` : escaped
}

function formatCell(val: any): string {
  if (val == null) return ''
  if (typeof val === 'object') return JSON.stringify(val)
  return String(val)
}

function download(content: string, filename: string) {
  const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', filename)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
} 